#!C:/Soft/Perl/bin/perl.exe
require PostConf;

if ($ENV{'REQUEST_METHOD'} ne 'POST') { $query = $ENV{'QUERY_STRING'}; }
else { read(STDIN, $query, $ENV{'CONTENT_LENGTH'}); }

$pathinfo = $ENV{'PATH_INFO'};

if ($pathinfo eq '') {
  print <<END;
Content-type: text/html; charset=windows-1251
Pragma: no-cache
Expires: now

<HTML><HEAD><TITLE>View Contest Results</TITLE></HEAD>
<BODY><H1>View Contest Results</H1>
<TABLE BORDER=1 CELLPADDING=4>
<TR><TH>File</TH><TH>Date</TH><TH>Size</TH><TH>Description</TH></TR>
END
opendir DIR, $workdir || die "cannot open directory $workdir";
@files = grep { /^[^\.]/ && /^[A-Za-z0-9][A-Za-z0-9\.\-_]{1,16}$/ && 
	-f "$workdir/$_" && -r "$workdir/$_"} readdir(DIR);
closedir DIR;
@list = ();
while ($fn = shift @files) {
  $data = '';  $info = '';
  open FILE, "$workdir/$fn" || die "cannot open $workdir/$fn";
  ($size,$time) = (stat FILE)[7,9];
  binmode FILE;
  sysread FILE, $data, 4096;
  close FILE;
  $data =~ s/\r\n/\n/g;
  ($info) = ($data =~ /\@contest\s+([^\r\n]+)\n/);
  $info = $1 if ($info =~ /^\s*\"(.*)\"$/);
  push @list, [$fn, $time, $size, $info];
}
@list = sort {$$b[1] <=> $$a[1]} @list;
while ($ref = shift @list) {
  ($fn, $time, $size, $info) = @$ref;
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime ($time);
  $date = sprintf ("%02d.%02d.%04d %02d:%02d:%02d", 
	$mday, $mon + 1, $year + 1900, $hour, $min, $sec);
  if ($info) {
    $info =~ s/&/&amp;/g;
    $info =~ s/</&lt;/g;
    $info =~ s/>/&gt;/g;
    $info = "<A HREF=monitor.pl/$fn>$info</A>"; }
  print "<TR><TD><A HREF=view.pl/$fn>$fn</A></TD><TD>$date</TD><TD>$size</TD><TD>$info</TD></TR>\n"
}
print "</TABLE></BODY></HTML>\n";
exit; }

die "invalid path" unless ($pathinfo =~ /^\/([A-Za-z0-9][A-Za-z0-9\.\-_]{1,16})$/);
$fn = $1;
open FILE, "$workdir/$fn" || die "cannot open $workdir/fn";
$size = (stat FILE)[7];
die "file $fn too long" if ($size > $maxlen);
binmode FILE;
sysread FILE, $data, $size;
close FILE;
($info) = ($data =~ /\r\n\032\r\n\@contest\s+([^\r\n]+)\r?\n/);
$ismon = ($info && $fn =~ /\.dat$/); 
$ctype = ($fn =~ /\.txt$/ || $fn =~ /\.dat$/ || $info) ? 'text/plain; charset=windows-1251' : 
 ($fn =~ /\.html?$/ ? 'text/html' : 'application/octet-stream');
print <<HEAD;
Content-type: $ctype
Pragma: no-cache
Expires: now

HEAD
print "--- testsys monitor file $fn ---\n"    if $ismon;
binmode STDOUT;
print $data;
